package com.relatev.minecraft.TRAttribute;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;

public class TRASupportUtils {

    private static boolean MaxHealthyBackward = false;
    private static Class<?> AttributeClazz;

    public static void init() {
        try {
            AttributeClazz = Class.forName("org.bukkit.attribute.Attribute");
        } catch (ClassNotFoundException ex) {
            MaxHealthyBackward = true;
            TRAttribute.mainPlugin.getLogger().info("getMaxHealthyBack 转换为旧版本模式!");
        }
    }
    
    public static String getEntityName(Entity ent){
        try {
            Method method = ent.getClass().getMethod("getName");
            return (String) method.invoke(ent);
        } catch (NoSuchMethodException ex) {
            return null;
        } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(TRASupportUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static double getLivingEntityMaxHealthy(LivingEntity lent) {
//        Class<?> lentclazz = lent.getClass();
        if (MaxHealthyBackward == false) {
            for (Object attr : AttributeClazz.getEnumConstants()) {
                try {
                    if (attr.getClass().getMethod("name").invoke(attr).equals("GENERIC_MAX_HEALTH")) {
                        return lent.getAttribute((org.bukkit.attribute.Attribute) attr).getValue();
                    }
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
                    Logger.getLogger(TRASupportUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            return 20;
        } else {
            return lent.getMaxHealth();
        }
    }

    public static void setLivingEntityMaxHealthy(LivingEntity lent, double hp) {
        if (MaxHealthyBackward == false) {
            for (Object attr : AttributeClazz.getEnumConstants()) {
                try {
                    if (attr.getClass().getMethod("name").invoke(attr).equals("GENERIC_MAX_HEALTH")) {
                        lent.getAttribute((org.bukkit.attribute.Attribute) attr).setBaseValue(hp);
                    }
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
                    Logger.getLogger(TRASupportUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            lent.setMaxHealth(hp);
        }
    }
}
